package com.wxcms.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.his.domain.PicSource;
import com.his.service.PicSourceService;
import com.wxcms.domain.DepEquipments;
import com.wxcms.domain.WxCpMyConfigStorage;
import com.wxcms.mapper.EquipmentDao;
import com.wxcms.mapper.WxCpDepartDao;
import com.wxcms.service.MyWxCpService;
import com.wxcms.service.impl.DodemWxServer;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpConfigStorage;
import me.chanjar.weixin.cp.bean.WxCpMessage;
import me.chanjar.weixin.cp.bean.WxCpMessage.WxArticle;
import net.sf.json.JSONObject;

@Transactional(value = "config", rollbackFor = Exception.class)  
@Service("WxPushService")
public class WxPushService extends HttpServlet    {

	@Autowired
	private MyWxCpService myWxCpService;

	@Autowired
	private EquipmentDao equipdao;

	@Autowired
	private PicSourceService picSourceService;
	
	@Autowired
	private WxCpDepartDao depdao;
	/**
	 * 
	 */
	private static final long serialVersionUID = -7145653650669365476L;
	
	private Logger log=Logger.getLogger(this.getClass());
	
	private Timer timer;
 
	
 
	
	private	String httpPath;
	
	@PostConstruct
	public void start() throws Exception {
		log.warn("初始化 推送sss  1000*60*2"+this);
//		 TimerTask task = new SynchroTimerTask();        
//         timer = new Timer(); 
//         //间隔：1小时
//    //   long period = 1000 * 60 * 60;    
//         //任务 延迟时间 执行 周期
//         timer.schedule(task, 1000*10 ,1000*60*10);
	} 
	public String GetHttpPath(String url,String token){
		 try {
			 //http://ln200.dongdiangufen.com/qyweix
	   //  httpPath= "http://ln200.dongdiangufen.com/qyweix";
        httpPath= "http://"+url+ "/qyweix/";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		 return httpPath;
	}
	@PreDestroy
	public void  stop () throws Exception {
	 
		log.warn("停止wxpush server！");
		timer.cancel();
	}
	
	 class SynchroTimerTask extends TimerTask {

		    @Override
		    public void run() {
		    	 
		    	try {
					Timestamp now = new Timestamp(System.currentTimeMillis());
					Calendar ca= Calendar.getInstance();
					ca.setTime(now);
					int hour=ca.get(Calendar.HOUR_OF_DAY);
					log.info(String.format("==========================判断夜间不推送,hour= %d  ==================\n ！"+this, hour) );
					if((hour<6)||(hour>19))
						
					{
						// 执行 同步天气到本机服务器
						
						
						// 在凌晨 控制同步，减少服务器的 其他时间的服务器占用
						
						
						log.info("夜间不推送！");
						return ;
					}
					now=null;
					Collection<DodemWxServer>    services=myWxCpService.getWxCpServices();
					//早上7点到晚上9点推送图片 
					
					
 
//				
//		        System.out.println("Synchro data to other servers."); 
					//读取需要推送的设备
					List<DepEquipments> lus = equipdao.getPushNeeded();
					log.warn("======需要推送的设备数量:"+lus.size()+this+"\n\n");
					int len = lus.size();
					int j=0;
					for (int i = 0; i < len; i++) {
						j++;
						DepEquipments dep = lus.get(i);
						String puid=dep.getPuid();
						String name=equipdao.getEquipName(puid);
						
						Timestamp d1 = new Timestamp(System.currentTimeMillis());
						dep.getLastTime();
						Calendar ca1=Calendar.getInstance();
						ca1.setTime(d1);
						ca1.add(Calendar.MINUTE, 5);
						
						//推送间隔小于5分钟不推送
					    if(	ca1.before(dep)){
						    log.warn("======推送间隔小于5分钟！\n");
						    equipdao.updatePushTime(puid,dep.getLastTime()/1000+"");
						    return;
					    }
					    // 读取该设备的最新图片
					    
						List<PicSource> pics = picSourceService.getNewPic("PICTURE", puid, 0,1); 
						
						
						log.warn("===需要推送的图片数量："+pics.size()+"\n\n");
						log.warn("===需要推送设备信息："+JSONObject.fromObject(dep).toString());
						
 
						boolean needpush=false;
						
						if(pics.size()<1){
						 
							log.error("该设备没有图片\n");
							
						}else {
							    PicSource pic=pics.get(0);
							     
								 {
							 
									//if(d.before(dep.getPushTime())){
									System.out.println(pic.getTtime() );
									System.out.println(dep.getLastTime());
									boolean newpic= (pic.getTtime().getTime()  >dep.getLastTime());
									  log.warn(pic.getTtime());
									  log.warn(dep.getLastTime());
								    log.warn(dep.getPuid()+"新图片推送判断："+newpic+"==="+j+this);
								    
								    if( newpic){
								    	  log.warn(dep.getPuid()+"==推送周期正常推送！");
										  needpush=true;
									}else{
										
										if(dep.getIsforce()==1){
											Timestamp d = new Timestamp(System.currentTimeMillis());
											boolean needforce=(d.getTime()  >dep.getPushTime());
											log.warn(dep.getPuid()+"==================强制推送判断！"+needforce+"=="+i+"==========="+j+this);
											
											if (needforce){
											  log.warn(dep.getPuid()+"==================强制推送！"+i+"==========="+j+this);
											  needpush=true;
											}
											
										}	
										
										
										 log.warn(dep.getPuid()+"==================推送周期未到！");
										
									}
 
								}
						 
							
						

						    if( needpush==true){
						    	//读取 该设备相关的 企业号 和  部门
						    	for( DodemWxServer server:services){
						    		WxCpMyConfigStorage cfg= (WxCpMyConfigStorage) server.getConfig();
						    		 String corpid=   cfg.getCorpId();
						    		 String province=   cfg.getProvince();
						    		 String url=cfg.getUrl();
						    		 String token=   server.getConfig().getToken();
						    		 log.warn(dep+"==================推送！"+corpid+"=="+token);
						    		 log.warn(dep.getPuid()+"==================推送！"+corpid+"=="+token+"=="+( token.contains("real")));
						    		 
						    		 //只推送到real 应用
						    		if( token.contains("real")){
									    	log.warn(dep.getPuid()+"==================推送1！"+dep.getPushTime());
									    
									    	log.warn("dep"+pic);
											
											equipdao.updatePushTime(puid,pic.getTtime().getTime()/1000+"");
											 
											WxArticle article1 = new WxCpMessage.WxArticle();
										
										//	System.out.println(httpPath+ "/mindex");
											StringBuffer _ul =new StringBuffer();
											Timestamp d = new Timestamp(System.currentTimeMillis());
											_ul.append( GetHttpPath(url,token)).append("mindex/").append(province).append("?puid=").append(puid).append("&type=imglist&tlong=").append(d.getTime());
					  
											String _wxul = server.oauth2buildAuthorizationUrl(_ul.toString(), "test");
								
											article1.setUrl(_wxul);
								
											article1.setPicUrl(httpPath+ "/equip/picsrc/"+pic.getPath()+pic.getName());
					 
										    article1.setDescription("设备号："+puid + "\n发送人：系统自动推送");
											 
											 
											article1.setTitle(name + "\n" + d.toString() );
											
											//读取设备的部门
											// for  内部异常try  避免出现单个 for 元素 造成的 for 循环停止，非必要时， 必要将try 用在 for 内部
											try {
												String depids = depdao.getDepIds(puid,corpid);
												
												log.warn(String.format("==推送的设备%s是，推送的企业号%s，推送的部门ids：%s！", puid,province,depids));
												
												d=null;
 
												
												if (depids.startsWith("|"))
													depids = depids.substring(1).trim();
												if (!depids.isEmpty())  {
													WxCpMessage m = WxCpMessage.NEWS().agentId(server.getConfig().getAgentId()).toParty(depids)
															.addArticle(article1).build();
												
													server.messageSend(m);
													article1=null;
													m=null;
													
													
													log.warn("==================推送完成！\n\n\n");
												}
											} catch (Exception e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
								      
						    		}
						    		 
						    	 }
						
						    }
						    pic=null;
						}
					    //slist.add(puid);
						dep=null;
//						
//						//推送间隔
//						try {
//							Thread.sleep(200);
//						} catch (InterruptedException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
					}
					
					/*//更新已经推送的时间
					if(slist.size()>0) 
					    equipdao.updatePushTime(StringUtils.join(slist, "|"));*/
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }

		}

}
